package asapIs134CK.womi.client.profile;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.PasswordTextBox;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;

public class DefaultUserDisplay extends Composite{
	private UserDisplay _parent;
	private VerticalPanel panel;
	private Label email;
	private TextBox txtEmail;
	private Label pwd;
	private TextBox txtPwd;
	private Button login;
	private Button signin;
	/**
	 * Create a remote service proxy to talk to the server-side Greeting service.
	 */
	private final RPCUserServiceAsync userService = GWT
			.create(RPCUserService.class);
	
	public DefaultUserDisplay(UserDisplay parent){
		_parent = parent;
		panel = new VerticalPanel();
		email = new Label("Email :");
		txtEmail = new TextBox();
		pwd = new Label("Password :");
		txtPwd = new PasswordTextBox();
		ClickHandler loginClickHandler = new ClickHandler(){

			public void onClick(ClickEvent event) {
				loginClick();
			}
			
		};
		login = new Button("Log in", loginClickHandler);
		ClickHandler signinClickHandler = new ClickHandler(){

			public void onClick(ClickEvent event) {
				signinClick();
				
			}
			
		};
		signin = new Button("Sign in", signinClickHandler );
		panel.add(email);
		panel.add(txtEmail);
		panel.add(pwd);
		panel.add(txtPwd);
		panel.add(login);
		panel.add(signin);
		initWidget(panel);
	}

	private void loginClick() {
		AsyncCallback<UserClient> callback = new AsyncCallback<UserClient>() {
			public void onFailure(Throwable caught) {
				// Show the RPC error message to the user
				Window.alert("The server could not be reached, please check your network connection.");
				_parent.displayDefault();
			}

			public void onSuccess(UserClient result) {
				// TODO : change name of this method
				if(result == null){
					Window.alert("Incorrect email / password.");
					_parent.displayDefault();
				}
				else {
					authenticated(result);
				}
			}
		};
		userService.authenticateUser(txtEmail.getText(), txtPwd.getText(), callback);
		panel.clear();
		panel.add(_parent.getWait());
	}
	
	private void authenticated(UserClient user){
		_parent.authenticated(user);
	}
	
	private void signinClick() {
		_parent.requestSignIn();
	}
}
